// src/components/timeline/Segment.tsx
import React, { useState, useEffect } from 'react';
import { useDraggable } from '@dnd-kit/core';
import { deleteSegment } from '@/services/project/index';
import { eventBus } from '@/utils/eventBus';
import './Segment.css';

// 片段类型枚举
export type SegmentType = 'text' | 'image' | 'video' | 'audio';

// 片段数据接口
export interface SegmentData {
    id: string;
    type: SegmentType;
    name: string;
    duration: number;
    start: number;
    clipSettings?:any;
    currentTrackIndex: number; // 轨道层级
    content?: string; // 文本内容
    src?: string; // 图片/视频/音频源地址
    thumbnail?: string; // 缩略图地址
    volume?: number; // 音量 (0-1)
    speed?: number; // 播放速度
    visible?: boolean; // 是否可见
}

// 组件Props接口
export interface SegmentProps {
    segment: SegmentData;
    pixelsPerSecond: number;
    isSelected?: boolean;
    onSelect?: (segment: SegmentData) => void;
    showPreview?: boolean;
    trackId?: string;
    draftId?: string;
}

const Segment: React.FC<SegmentProps> = ({ segment, pixelsPerSecond, isSelected = false, onSelect, trackId, draftId }) => {
    // 添加鼠标悬停状态
    const [isHovered, setIsHovered] = useState(false);
    // 添加视频缩略图状态
    const [videoThumbnail, setVideoThumbnail] = useState<string | null>(null);
    // 添加视频帧序列状态
    const [videoFrames, setVideoFrames] = useState<string[]>([]);
    // 计算片段的宽度和位置
    const width = segment.duration * pixelsPerSecond;
    const left = segment.start * pixelsPerSecond;
    console.log('segment', segment);

    // 生成视频帧序列的函数
    const generateVideoFrames = (videoSrc: string, duration: number): Promise<string[]> => {
        return new Promise((resolve, reject) => {
            const video = document.createElement('video');
            video.crossOrigin = 'anonymous';
            video.preload = 'metadata';

            const frames: string[] = [];
            const frameCount = Math.ceil(duration); // 每秒一帧
            let currentFrame = 0;

            const captureFrame = () => {
                const canvas = document.createElement('canvas');
                const ctx = canvas.getContext('2d');

                if (!ctx) {
                    reject(new Error('无法创建canvas上下文'));
                    return;
                }

                // 设置canvas尺寸 - 每帧的宽度
                const frameWidth = 200 / frameCount; // 总宽度200px，平均分配给每帧
                canvas.width = frameWidth;
                canvas.height = 112; // 16:9 比例

                // 绘制视频帧到canvas
                ctx.drawImage(video, 0, 0, canvas.width, canvas.height);

                // 转换为base64
                const frameData = canvas.toDataURL('image/jpeg', 0.8);
                frames.push(frameData);

                currentFrame++;
                if (currentFrame < frameCount) {
                    // 继续下一帧
                    video.currentTime = currentFrame;
                } else {
                    // 所有帧都截取完成
                    resolve(frames);
                }
            };

            video.onloadedmetadata = () => {
                // 开始截取第一帧
                video.currentTime = 0.1;
            };

            video.onseeked = () => {
                captureFrame();
            };

            video.onerror = () => {
                reject(new Error('视频加载失败'));
            };

            video.src = videoSrc;
        });
    };

    // 生成视频缩略图的函数（保留作为备用）
    const generateVideoThumbnail = (videoSrc: string): Promise<string> => {
        return new Promise((resolve, reject) => {
            const video = document.createElement('video');
            video.crossOrigin = 'anonymous';
            video.preload = 'metadata';

            video.onloadedmetadata = () => {
                // 设置视频时间为第一帧
                video.currentTime = 0.1;
            };

            video.onseeked = () => {
                const canvas = document.createElement('canvas');
                const ctx = canvas.getContext('2d');

                if (!ctx) {
                    reject(new Error('无法创建canvas上下文'));
                    return;
                }

                // 设置canvas尺寸
                canvas.width = 200;
                canvas.height = 112; // 16:9 比例

                // 绘制视频帧到canvas
                ctx.drawImage(video, 0, 0, canvas.width, canvas.height);

                // 转换为base64
                const thumbnail = canvas.toDataURL('image/jpeg', 0.8);
                resolve(thumbnail);
            };

            video.onerror = () => {
                reject(new Error('视频加载失败'));
            };

            video.src = videoSrc;
        });
    };

    // 处理视频帧序列生成
    useEffect(() => {
        if (segment.type === 'video' && segment.src && videoFrames.length === 0) {
            // 如果是图片文件，跳过视频处理
            if (isImageFile(segment.src)) {
                return;
            }

            generateVideoFrames(segment.src, segment.duration)
                .then((frames) => {
                    setVideoFrames(frames);
                })
                .catch((error) => {
                    console.warn('生成视频帧序列失败:', error);
                    // 如果帧序列生成失败，回退到单帧缩略图
                    generateVideoThumbnail(segment.src!)
                        .then((thumbnail) => {
                            setVideoThumbnail(thumbnail);
                        })
                        .catch((thumbError) => {
                            console.warn('生成视频缩略图也失败:', thumbError);
                        });
                });
        }
    }, [segment.type, segment.src, segment.duration, videoFrames.length]);

    // 配置@dnd-kit拖拽
    const { attributes, listeners, setNodeRef, transform, isDragging } = useDraggable({
        id: segment.id,
        data: {
            type: 'segment',
            segment,
        },
    });
    // isDragging 可用于拖拽时的视觉反馈，暂时未使用

    // 配置左侧调整手柄拖拽
    const {
        attributes: leftResizeAttributes,
        listeners: leftResizeListeners,
        setNodeRef: setLeftResizeNodeRef,
        transform: leftResizeTransform,
        isDragging: isLeftResizing,
    } = useDraggable({
        id: `${segment.id}-left-resize`,
        data: {
            type: 'resize-left',
            segment,
        },
    });
    // isLeftResizing 可用于调整时的视觉反馈，暂时未使用

    // 配置右侧调整手柄拖拽
    const {
        attributes: rightResizeAttributes,
        listeners: rightResizeListeners,
        setNodeRef: setRightResizeNodeRef,
        transform: rightResizeTransform,
        isDragging: isRightResizing,
    } = useDraggable({
        id: `${segment.id}-right-resize`,
        data: {
            type: 'resize-right',
            segment,
        },
    });
    // isRightResizing 可用于调整时的视觉反馈，暂时未使用

    // 检查是否为图片文件
    const isImageFile = (src: string): boolean => {
        const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg'];
        return imageExtensions.some((ext) => src.toLowerCase().includes(ext));
    };

    // 获取片段背景样式
    const getSegmentBackground = (): React.CSSProperties => {
        // 如果是图片类型且有src，使用图片作为背景
        if (segment.type === 'image' && segment.src) {
            return {
                backgroundImage: `url(${segment.src})`,
                backgroundSize: 'cover',
                backgroundPosition: 'center',
                backgroundRepeat: 'no-repeat',
            };
        }

        // 如果是视频类型但src是图片文件，直接使用图片作为背景
        if (segment.type === 'video' && segment.src && isImageFile(segment.src)) {
            return {
                backgroundImage: `url(${segment.src})`,
                backgroundSize: 'cover',
                backgroundPosition: 'center',
                backgroundRepeat: 'no-repeat',
            };
        }

        // 如果是视频类型且有帧序列，使用帧序列作为背景
        if (segment.type === 'video' && videoFrames.length > 0) {
            // 创建帧序列的CSS渐变背景
            const frameGradients = videoFrames
                .map((frame, index) => {
                    const startPercent = (index / videoFrames.length) * 100;
                    return `url(${frame}) ${startPercent}% 0% / ${100 / videoFrames.length}% 100% no-repeat`;
                })
                .join(', ');

            return {
                background: frameGradients,
                backgroundSize: '100% 100%',
                backgroundRepeat: 'no-repeat',
            };
        }

        // 如果是视频类型且有单帧缩略图，使用缩略图作为背景
        if (segment.type === 'video' && videoThumbnail) {
            return {
                backgroundImage: `url(${videoThumbnail})`,
                backgroundSize: 'cover',
                backgroundPosition: 'center',
                backgroundRepeat: 'no-repeat',
            };
        }

        // 如果是视频类型但还没有任何缩略图，使用默认颜色
        if (segment.type === 'video') {
            return {
                backgroundColor: 'rgba(54, 46, 204, 0.8)', // 蓝色
            };
        }

        // 其他情况使用默认颜色
        switch (segment.type) {
            case 'text':
                return { backgroundColor: '#9C4937' }; // 深红色
            case 'image':
                return { backgroundColor: 'rgba(40, 167, 69, 0.8)' }; // 绿色
            case 'audio':
                return { backgroundColor: 'rgba(220, 53, 69, 0.8)' }; // 红色
            default:
                return { backgroundColor: 'rgba(108, 117, 125, 0.8)' }; // 灰色
        }
    };

    // 处理点击选中
    const handleClick = (event: React.MouseEvent) => {
        event.stopPropagation();
        if (onSelect) {
            onSelect(segment);
        }
    };

    // 处理删除按钮点击事件
    const handleDeleteClick = async (event: React.MouseEvent) => {
        event.stopPropagation(); // 防止冒泡到片段的点击事件

        if (!trackId || !draftId) {
            console.error('删除片段失败: 缺少 trackId 或 draftId');
            return;
        }
        try {
            // 调用删除片段的 API
            await deleteSegment(draftId, trackId, segment.id);
            // 发送事件总线通知，获取最新草稿数据
            eventBus.emit('draft:updated', { draftId });
        } catch (error) {
            console.error('删除片段失败:', error);
        }
    };

    // 处理鼠标进入
    const handleMouseEnter = () => {
        setIsHovered(true);
    };

    // 处理鼠标离开
    const handleMouseLeave = () => {
        setIsHovered(false);
    };

    // 渲染片段内容
    const renderContent = () => {
        switch (segment.type) {
            case 'text':
                return (
                    <div className="segment-content text-content">
                        <span className="segment-text">{segment.content || segment.name}</span>
                    </div>
                );
            case 'image':
                return (
                    <div className="segment-content image-content">
                        <span className="segment-text">{segment.name}</span>
                    </div>
                );
            case 'video':
                return (
                    <div className="segment-content video-content">
                        <span className="segment-text">{segment.name}</span>
                        <div className="segment-duration">{Math.round(segment.duration)}s</div>
                    </div>
                );
            case 'audio':
                return (
                    <div className="segment-content audio-content">
                        <div className="audio-waveform">
                            {/* 简化的音频波形显示 */}
                            <div className="waveform-bars">
                                {Array.from({ length: Math.min(20, Math.floor(width / 10)) }).map((_, i) => (
                                    <div key={i} className="waveform-bar" style={{ height: `${20 + Math.random() * 60}%` }} />
                                ))}
                            </div>
                        </div>
                        <div className="segment-duration">{Math.round(segment.duration)}s</div>
                    </div>
                );
            default:
                return (
                    <div className="segment-content">
                        <span className="segment-text">{segment.name}</span>
                    </div>
                );
        }
    };

    return (
        <>
            <div
                ref={setNodeRef}
                className={`segment ${segment.type}-segment`}
                style={{
                    left: `${left}px`,
                    width: `${width}px`,
                    top: '2px',
                    position: 'absolute',
                    height: '28px',
                    border: isSelected ? '2px solid #007acc' : '1px solid #ccc',
                    borderRadius: '4px',
                    cursor: 'grab',
                    userSelect: 'none',
                    zIndex: 1,
                    transform: transform ? `translate3d(${transform.x}px, ${transform.y}px, 0)` : undefined,
                    ...getSegmentBackground(), // 使用新的背景样式函数
                }}
                onClick={handleClick}
                onMouseEnter={handleMouseEnter}
                onMouseLeave={handleMouseLeave}
                {...attributes}
                {...listeners}
            >
                {renderContent()}
                {/* 垃圾桶删除按钮 */}
                {isHovered && (
                    <div
                        className="delete-button"
                        style={{
                            position: 'absolute',
                            top: '-1px',
                            right: '-1px',
                            width: '20px',
                            height: '20px',
                            backgroundColor: '#fff',
                            borderRadius: '50%',
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            boxShadow: '0 2px 4px rgba(0, 0, 0, 0.2)',
                            zIndex: 1001,
                            transition: 'all 0.2s ease',
                            cursor: 'pointer',
                            fontSize: '12px',
                        }}
                        onMouseEnter={(e) => {
                            e.currentTarget.style.backgroundColor = '#f8f9fa';
                            e.currentTarget.style.transform = 'scale(1.1)';
                        }}
                        onMouseLeave={(e) => {
                            e.currentTarget.style.backgroundColor = '#fff';
                            e.currentTarget.style.transform = 'scale(1)';
                        }}
                        onClick={handleDeleteClick}
                    >
                        🗑️
                    </div>
                )}

                {/* 左侧调整手柄 */}
                <div
                    ref={setLeftResizeNodeRef}
                    className="resize-handle resize-handle-left"
                    style={{
                        position: 'absolute',
                        left: '0',
                        top: '0',
                        width: '8px',
                        height: '100%',
                        cursor: 'ew-resize',
                        backgroundColor: 'transparent',
                        opacity: 1,
                        transform: leftResizeTransform ? `translate3d(${leftResizeTransform.x}px, ${leftResizeTransform.y}px, 0)` : undefined,
                    }}
                    {...leftResizeAttributes}
                    {...leftResizeListeners}
                />

                {/* 右侧调整手柄 */}
                <div
                    ref={setRightResizeNodeRef}
                    className="resize-handle resize-handle-right"
                    style={{
                        position: 'absolute',
                        right: '0',
                        top: '0',
                        width: '8px',
                        height: '100%',
                        cursor: 'ew-resize',
                        backgroundColor: 'transparent',
                        opacity: 1,
                        transform: rightResizeTransform ? `translate3d(${rightResizeTransform.x}px, ${rightResizeTransform.y}px, 0)` : undefined,
                    }}
                    {...rightResizeAttributes}
                    {...rightResizeListeners}
                />
            </div>
        </>
    );
};

export default Segment;
